'use strict';

const Controller = require('egg').Controller;

class AdminController extends Controller {

  async index() {
    this.ctx.body = '这是api';
  }

  // 登录
  async login() {
    const name = this.ctx.request.body.name;
    const pwd = this.ctx.request.body.password;
    const sql = 'SELECT name FROM user WHERE name="' + name + '"AND password="' + pwd + '"';
    const res = await this.app.mysql.query(sql);
    let body = {};
    if (res.length !== 1) {
      body = {
        msg: '登陆失败',
        code: 500,
      };
    } else {
      if (!this.ctx.session.SESSION_ADMIN) {
        const date = Date.parse(new Date());
        this.ctx.session.SESSION_ADMIN = 'admin_' + date;
      }
      body = {
        msg: '登陆成功',
        code: 200,
      };
    }
    this.ctx.body = body;
  }

  // 推出
  async logout() {
    this.ctx.session.SESSION_ADMIN = null;
    const session = this.ctx.session.SESSION_ADMIN;
    console.log(session);
    this.ctx.body = { session };
  }

  // 新增文章
  async addArticle() {
    const newArticle = this.ctx.request.body;
    const date = Date.parse(new Date()) / 1000;
    newArticle.addTime = date;
    newArticle.updateTime = date;
    const result = await this.app.mysql.insert('article', newArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;
    if (insertSuccess) {
      this.ctx.body = {
        msg: '添加成功',
        code: 200,
        insertId,
      };
    } else {
      this.ctx.body = {
        msg: '添加失败',
        code: 500,
        insertId,
      };
    }
  }

  // 修改文章
  async updateArticle() {
    const newArticle = this.ctx.request.body;
    const date = Date.parse(new Date()) / 1000;
    newArticle.updateTime = date;
    const result = await this.app.mysql.update('article', newArticle, {
      where: {
        id: newArticle.id,
      },
    });
    const updateSuccess = result.affectedRows === 1;
    if (updateSuccess) {
      this.ctx.body = {
        msg: '修改成功',
        code: 200,
      };
    } else {
      this.ctx.body = {
        msg: '修改失败',
        code: 500,
      };
    }
  }

  // 获取文章列表通过id(或所有（id=0）)或者状态
  async getArticleList() {
    const type_id = this.ctx.params.type_id;
    const status = this.ctx.params.status;
    let sql = 'SELECT ' +
      'article.id as id,' +
      'article.title as title,' +
      'type.typeName as type,' +
      'article.status as status,' +
      'FROM_UNIXTIME(article.addTime,"%Y-%m-%d %H:%i:%s" ) as addTime,' +
      'FROM_UNIXTIME(article.updateTime,"%Y-%m-%d %H:%i:%s" ) as updateTime,' +
      'article.view_count as view_count ' +
      'FROM article LEFT JOIN type ON article.type_id = type.id';
    if ((type_id / 1) !== 0) {
      sql = sql + ' WHERE type_id=' + type_id;
    }
    if ((status / 1) !== -1 && (type_id / 1) === 0) {
      sql = sql + ' WHERE status=' + status;
    }
    if ((status / 1) !== -1 && (type_id / 1) !== 0) {
      sql = sql + ' AND status=' + status;
    }
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      list: res,
    };
  }

  // 获取文章详情
  async getArticleDetail() {
    const id = this.ctx.params.id;
    const sql = 'SELECT ' +
      'article.id as id,' +
      'type.id as typeId,' +
      'article.title as title,' +
      'type.typeName as type,' +
      'article.introduce as introduce,' +
      'article.content as content ' +
      'FROM article LEFT JOIN type ON article.type_id = type.id ' +
      'WHERE article.id = ' + id;
    console.log(sql);
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      data: res[0],
    };
  }

  // 删除文章
  async delArticleById() {
    const id = this.ctx.request.body.id;
    const result = await this.app.mysql.update('article', {
      status: 2,
    }, {
      where: { id },
    });
    const delSuccess = result.affectedRows === 1;
    if (delSuccess) {
      this.ctx.body = {
        msg: '删除成功',
        code: 200,
      };
    } else {
      this.ctx.body = {
        msg: '删除失败',
        code: 500,
      };
    }
  }

  // 文章列表
  // 获取文章类别
  async getTypeList() {
    const sql = 'SELECT *  FROM type ORDER BY orderNum';
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      list: res,
    };
  }

  // 获取文章类别详细
  async getTypeListInfo() {
    const sql = 'SELECT type.id AS id,typeName,orderNum,COUNT(article.type_id) AS total ' +
      'FROM article LEFT JOIN type ON article.type_id = type.id ' +
      'GROUP BY type.id ' +
      'ORDER BY orderNum';
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      list: res,
    };
  }

  // 新增或编辑列表
  async addType() {
    const newType = this.ctx.request.body;
    let res = '';
    if (!newType.id) {
      delete newType.id;
      res = await this.app.mysql.insert('type', newType);
    } else {
      res = await this.app.mysql.update('type', newType);
    }
    const insertSuccess = res.affectedRows === 1;
    if (insertSuccess) {
      this.ctx.body = {
        msg: '添加成功',
        code: 200,
      };
    } else {
      this.ctx.body = {
        msg: '添加失败',
        code: 500,
      };
    }
  }


  // 数据展示
  async articleAddTime() {
    const sql = 'SELECT' +
      'FROM_UNIXTIME( addTime,"%Y/%m/%d") days,count( id )' +
      ' FROM article' +
      ' WHERE status = 1' +
      ' GROUP BY days';
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      list: res,
    };
  }

  // 近n天的访问量
  async visitCount() {
    const sql = 'SELECT FROM_UNIXTIME( visit_time,"%Y/%m/%d") days, count( id ) as total' +
      ' FROM visit ' +
      ' GROUP BY days';
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      list: res,
    };
  }
}

module.exports = AdminController;
